package ui.activity.home;

import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.Matrix;
import android.os.Build;
import android.os.Bundle;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v7.widget.DefaultItemAnimator;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Html;
import android.text.Spanned;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.widget.TextView;

import com.jakewharton.rxbinding.view.RxView;

import net.ck.hzq.R;
import net.ck.hzq.TobuyApplication;

import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.concurrent.TimeUnit;

import javax.inject.Inject;

import Utils.ResourcesManager;
import base.BaseAct;
import butterknife.BindView;
import cn.finalteam.loadingviewfinal.HeaderAndFooterRecyclerViewAdapter;
import cn.finalteam.loadingviewfinal.OnDefaultRefreshListener;
import cn.finalteam.loadingviewfinal.OnLoadMoreListener;
import cn.finalteam.loadingviewfinal.PtrClassicFrameLayout;
import cn.finalteam.loadingviewfinal.PtrFrameLayout;
import cn.finalteam.loadingviewfinal.RecyclerViewFinal;
import cn.sharesdk.framework.Platform;
import cn.sharesdk.framework.PlatformActionListener;
import event.NetErrorEvent;
import ui.activity.home.biz.CreditCardsBiz;
import ui.activity.home.component.DaggerCreditCardsComponent;
import ui.activity.home.contract.CreditCardsContract;
import ui.activity.home.module.CreditCardsModule;
import ui.activity.home.presenter.CreditCardsPresenter;
import ui.adapter.CreditCardsAdapter;
import ui.model.CreditCardsBean;
import util.CommonViewUtil;
import util.LogUtils;
import util.StringUtils;
import util.ToastUtils;


/**
 * 信用卡
 * Created by chenjian on 2019/6/6
 */

public class CreditCardsAct extends BaseAct implements CreditCardsContract.View {


    @Inject
    CreditCardsPresenter presenter;
    @Inject
    CreditCardsBiz biz;

    @BindView(R.id.pull_refresh_rv)
    RecyclerViewFinal rv;
    @BindView(R.id.pull_refresh_ptr)
    PtrClassicFrameLayout ptr;
    @BindView(R.id.needsx)
    TextView needsx;

    CreditCardsAdapter adp;
    CreditCardsBean creditCardsBean;

    View footerView;
    TextView share;
    TextView textInfo1;
    TextView textInfo2;
    TextView textInfo3;
    String shareData;


    @Override
    protected void setRoot() {
//        setTitleBar(R.color.colorBlue);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
            Window window = getWindow();
            window.clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
            window.getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                    | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);
            window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
            window.setStatusBarColor(Color.TRANSPARENT);
        }
        setContentView(R.layout.activity_credit_cards);

    }

    @Override
    protected void setup() {
        DaggerCreditCardsComponent.builder().creditCardsModule(new CreditCardsModule(this)).build().inject(this);
        setToolBar(getResources().getString(R.string.re_men), "");
        presenter.setBiz(biz);
    }


    @Override
    protected void init(@Nullable Bundle savedInstanceState) {
        CommonViewUtil.setDarw(needsx, this, R.mipmap.credit_share, -1, -1, -1);
        footerView = getLayoutInflater().inflate(R.layout.foot_credit_card,
                (ViewGroup) rv.getParent(), false);
        share = footerView.findViewById(R.id.credit_card_share);
        textInfo1 = footerView.findViewById(R.id.credit_card_title1);
        textInfo2 = footerView.findViewById(R.id.credit_card_title2);
        textInfo3 = footerView.findViewById(R.id.credit_card_title3);
        String info1 = "1.点击本页面右上角<font color=#FFC525 >分享按钮，</font>分享给好友。";
        Spanned str1 = Html.fromHtml(info1);
        textInfo1.setText(str1);
        String info2 = "2.分享成功后，<font color=#FFC525 >百元红包发放至您的好钻钱账户，</font>可在“我的红包”中查看使用";
        Spanned str2 = Html.fromHtml(info2);
        textInfo2.setText(str2);
        String info3 = "3.通过分享后，好友办卡成功或开卡成功，<font color=#FFC525 >可获得80-180元现金奖励，</font>现金奖励将发放至APP钱包里，可直接提现";
        Spanned str3 = Html.fromHtml(info3);
        textInfo3.setText(str3);
        creditCardsBean = (CreditCardsBean) getIntent().getSerializableExtra("info");
//        setToolBar(StringUtils.isEmpty(getIntent().getStringExtra("name")) ? "" : getIntent().getStringExtra("name"), "");
        rv.setLayoutManager(new LinearLayoutManager(CreditCardsAct.this));
        rv.setItemAnimator(new DefaultItemAnimator());
//        rv.addItemDecoration(new DividerItemDecoration(this, LinearLayoutManager.VERTICAL));
        ptr.setLastUpdateTimeRelateObject(this);
        ptr.disableWhenHorizontalMove(true);
        rv.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void loadMore() {
            }
        });
        ptr.setOnRefreshListener(new OnDefaultRefreshListener() {
            @Override
            public void onRefreshBegin(PtrFrameLayout frame) {
                presenter.getList(true, creditCardsBean.getId());
            }
        });
        rv.setOnItemClickListener(new HeaderAndFooterRecyclerViewAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView.ViewHolder holder, int position) {

            }
        });
        RxView.clicks(needsx)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toShare());
        RxView.clicks(share)
                .compose(this.<Void>bindToLifecycle())
                .throttleFirst(500, TimeUnit.MILLISECONDS)
                .subscribe(Void -> presenter.toShare());
        ptr.autoRefresh(true);
    }


    @Override
    public void onNetErrorEvent(NetErrorEvent event) {
        super.onNetErrorEvent(event);
    }

    @Override
    protected void onNetError(NetErrorEvent event) {

    }


    @Override
    protected void onStop() {
        super.onStop();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        biz.onDestory();
    }


    @Override
    public void upDateUI(List<CreditCardsBean> bean) {
        if (adp == null) {
            adp = new CreditCardsAdapter(CreditCardsAct.this, bean);
            addHeadView();
            rv.setAdapter(adp);
        } else {
            adp.notifyDataSetChanged();
        }
    }

    @Override
    public void upDataShare(String data) {
        shareData = data;
        new Thread(new Runnable() {
            @Override
            public void run() {
                try {
                    onOneKeyShare();
                } catch (Exception e) {
                    ToastUtils.shortToast(e.getMessage() + "");
                    e.printStackTrace();

                }
            }
        }).start();
    }

    @Override
    public void setViewEnable(boolean isShow) {
        needsx.setEnabled(isShow);
        share.setEnabled(isShow);
    }

    @Override
    public void refreshComplete() {
        ptr.onRefreshComplete();
    }


    @Override
    public void loadMoreComplete() {
        rv.onLoadMoreComplete();
    }

    @Override
    public void hasLoadMore(boolean b) {
        rv.setHasLoadMore(b);
    }


    private void addHeadView() {
        View headView = getLayoutInflater().inflate(R.layout.hight_empty_layout,
                (ViewGroup) rv.getParent(), false);
        if (adp != null && adp.getHeaderLayout() == null) {
            adp.addHeaderView(headView);
        }
        if (adp != null && adp.getFooterLayout() == null) {
            adp.addFooterView(footerView);
        }
    }

    /**
     * 一键分享
     */
    private void onOneKeyShare() {
        String url = creditCardsBean.getLink() + "?shareNo=" + shareData + "&customId=" + TobuyApplication.getCustomId() + "&pId=" + creditCardsBean.getId();
        LogUtils.d(url);
        LogUtils.d(creditCardsBean.getName());
        LogUtils.d(creditCardsBean.getComment());
        LogUtils.d(creditCardsBean.getSmallImg()+"");
        cn.sharesdk.onekeyshare.OnekeyShare oks = new cn.sharesdk.onekeyshare.OnekeyShare();
        oks.setAddress(url);
        ResourcesManager manager = ResourcesManager.getInstace(CreditCardsAct.this);
        oks.setTitle(creditCardsBean.getName());//标题
        oks.setText(creditCardsBean.getComment());//内容
        oks.setUrl(url);//链接
        oks.setTitleUrl(url);
        Bitmap thumbBmp = null;
        if (StringUtils.isEmpty(creditCardsBean.getSmallImg())) {
            thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_new);
        } else {
            try {
                Bitmap bitmap = BitmapFactory.decodeStream(new URL(creditCardsBean.getSmallImg()).openStream());
                thumbBmp = Bitmap.createScaledBitmap(bitmap, 120, 150, true);
//                msg.thumbData = Util.bmpToByteArray(createBitmapThumbnail(thumbBmp, true), true);
            } catch (Exception e) {
                LogUtils.d("-----------");
                thumbBmp = BitmapFactory.decodeResource(getResources(), R.mipmap.logo_new);
            }
        }
        oks.setImageData(thumbBmp);
        oks.setCallback(new PlatformActionListener() {
            @Override
            public void onComplete(Platform platform, int i, HashMap<String, Object> hashMap) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " completed at " + msg;
                Message message = new Message();
                message.obj = text;
//                handler.sendMessage(message);
            }

            @Override
            public void onError(Platform platform, int i, Throwable throwable) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + "caught error at " + msg;
                Message message = new Message();
                message.obj = text;
            }

            @Override
            public void onCancel(Platform platform, int i) {
                String msg = ResourcesManager.actionToString(i);
                String text = platform.getName() + " canceled at " + msg;
                Message message = new Message();
                message.obj = text;
            }
        });
        oks.show(CreditCardsAct.this);
    }


    /**
     * 设置缩略图
     *
     * @param bitMap
     * @param needRecycle
     * @return
     */
    public static Bitmap createBitmapThumbnail(Bitmap bitMap, boolean needRecycle) {
        int width = bitMap.getWidth();
        int height = bitMap.getHeight();
        // 设置想要的大小
        int newWidth = 80;
        int newHeight = 80;
        // 计算缩放比例
        float scaleWidth = ((float) newWidth) / width;
        float scaleHeight = ((float) newHeight) / height;
        // 取得想要缩放的matrix参数
        Matrix matrix = new Matrix();
        matrix.postScale(scaleWidth, scaleHeight);
        // 得到新的图片
        Bitmap newBitMap = Bitmap.createBitmap(bitMap, 0, 0, width, height,
                matrix, true);
        if (needRecycle) bitMap.recycle();
        return newBitMap;
    }

}
